package com.zkn.component.office.excel;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.zkn.component.office.excel.handler.ExcelFieldHandler;
import com.zkn.component.office.excel.handler.ExcelTemplateHandler;
import com.zkn.component.office.excel.template.ExcelTemplate;
import com.zkn.component.office.excel.utils.ExcelUtils;

/**
 * Excel Writer
 * @author frank.su 
 * @date 2017/08/01
 */
public class ExcelWriter {
	
	/*
	 * TODO
	 * 1. Create Workbook.
	 * 2. Write Data to Workbook.
	 * 3. Output Workbook.
	 * 4. Release output.
	 */

	/**
	 * addLastColumn2Excel
	 * @throws Exception
	 * @author Frank Su
	 */
	public static void addLastColumn2Excel(String filepath, List<?> dataList) throws Exception{
		addLastColumn2Excel(filepath, dataList, 0);
	}
	
	/**
	 * addLastColumn2Excel
	 * @throws Exception
	 * @author Frank Su
	 */
	public static void addLastColumn2Excel(String filepath, List<?> dataList, int sheetIndex) throws Exception{
		ExcelUtils.addLastColumn2Excel(filepath, dataList);
	}
	
	
	/**
	 * writeObject2Excel
	 * @throws Exception
	 * @author Frank Su
	 */
	public static <T> void writeObject2Excel(String filepath, List<T> dataList) throws Exception{
		
		if(dataList == null || dataList.isEmpty()){
			return ;
		}
		
		List<Map<String,Object>> mapList= new ArrayList<Map<String,Object>>();
		for(int i = 0; i < dataList.size(); i ++){
			mapList.add(ExcelFieldHandler.handle(dataList.get(i)));
		}	
		
		ExcelUtils.writeMap2Excel(filepath, mapList);
	}
	
	/**
	 * writeMap2Excel
	 * @param filepath
	 * @param dataList: field - excel value
	 * @param fieldTitleMap: field - excel title
	 * @throws Exception
	 * @author Frank Su
	 */
	public static void writeMap2Excel(String filepath, List<Map<String,Object>> dataList, Map<String, String> fieldTitleMap) throws Exception{
		
		if(dataList == null || dataList.isEmpty()){
			return ;
		}
		
		List<Map<String,Object>> mapList= new ArrayList<Map<String,Object>>();
		for (Map<String, Object> datamap : dataList) {
			Map<String, Object> map = new LinkedHashMap<String, Object>();
			for (Entry<String, String> fieldTitle : fieldTitleMap.entrySet()) {
				map.put(fieldTitle.getValue(), datamap.get(fieldTitle.getKey()));
			}
			mapList.add(map);
		}
		
		ExcelUtils.writeMap2Excel(filepath, mapList);
	}
	
	/**
	 * writeMap2Excel
	 * @throws Exception
	 * @author Frank Su
	 */
	public static void writeMap2Excel(String filepath, List<Map<String,Object>> dataList) throws Exception{
		ExcelUtils.writeMap2Excel(filepath, dataList);
	}
	
	/**
	 * writeData2ExcelTemplate
	 * @throws Exception
	 * @author Frank Su
	 */
	public static void writeData2ExcelTemplate(ExcelTemplate excelTemplate) throws Exception{
		new ExcelTemplateHandler(excelTemplate).handle();
	}
}
